package com.lingz.manager.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.lingz.manager.common.utils.SecurityUtil;
import com.lingz.manager.modules.base.entity.User;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @author fanyoucai
 */
@Configuration
@MapperScan({"com.lingz.manager.modules.*.mapper","com.lingz.manager.modules.*.*.mapper"})
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * 分页插件，自动识别数据库类型
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        User currUser = SecurityUtil.getCurrUserStatic();
        if (null != currUser) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("createBy", currUser.getUsername(), metaObject);
            this.setFieldValByName("updateTime", new Date(), metaObject);
            this.setFieldValByName("updateBy", currUser.getUsername(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        User currUser = SecurityUtil.getCurrUserStatic();
        if (null != currUser) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
            this.setFieldValByName("updateBy", currUser.getUsername(), metaObject);

        }
    }

    @Bean
    public ExpandSqlInjector expandSqlInjector() {
        return new ExpandSqlInjector();
    }
}
